package com.ruoyi.front.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.front.domain.Account;
import com.ruoyi.front.dto.PassDTO;
import com.ruoyi.front.mapper.AccountMapper;
import com.ruoyi.front.service.AccountService;
import com.ruoyi.front.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private TokenUtil tokenUtil;
    @Override
    public R login(String username, String password) {
        Account account = accountMapper.getAccountByUsername(username);
        if (account == null || !account.getPassword().equals(password)){
            return R.fail("用户名或密码错误");
        }
        String token = tokenUtil.getToken(String.valueOf(account.getAccountId()), account.getUsername());
        return R.ok(token);
    }

    @Override
    public R updatePass(PassDTO passDTO,String token) {
        Map<String, String> map = tokenUtil.parseToken(token);
        String accountId = map.get("accountId");
        Account account = accountMapper.getAccountById(accountId);
        if (account!= null && account.getPassword().equals(passDTO.getOldPass())){
            account.setPassword(passDTO.getNewPass());
            accountMapper.updatePass(account);
            return R.ok("修改密码成功");
        }
        return R.fail("旧密码错误");
    }
}
